<?php
/**
* Add an entity in [ albums ]
*/

$albums = new albums();

if($variable->post('add-action', 'string', ''))
{
	# Posted Data: Apply security
	$data = $variable->post('albums', 'array', array());
	
	# Immediately activate the record
	$data['is_active']   = 'Y';
	$data['is_approved'] = 'Y';
	
	# When this record is added for the first time?
	$data['added_on'] = 'UNIX_TIMESTAMP(CURRENT_TIMESTAMP())';
	
	$data['subdomain_id'] = $subdomain_id;
	
	$data['album_code'] = tools::unique_code();
	
	$data['album_folder'] = str_replace('\\', '/', $data['album_folder']);
	if(!is_dir($data['album_folder']) || !is_writable($data['album_folder']))
	{
		$messenger = new messenger('error', '<strong>Rejected</strong>: The album path you supplied is NOT accessible.');

		$details = array();
		
		if(isset($_SESSION['attempt_albums']))
		{
			$details = $_SESSION['attempt_albums'];
			unset($_SESSION['attempt_albums']);
		}
	
		# Validate it against the parameters in itself, plus those what we need.
		$details = $albums->validate('add', $details);
		$smarty->assign('albums', $details);
	}
	else
	{
		if($album_id = $albums->add($data, false))
		{
			# Send a welcome message (and ask to authenticate), if applies, eg. as in Membership
			# $albums->welcome_first($album_id);
	
			$messenger = new messenger('success', 'The record has been added.');
	
			stopper::url(url::last_page('albums-list.php'));
			# stopper::url('albums-add-successful.php');
			# stopper::url('albums-list.php');
			
			# Once successfully added, as the admin user to edit the data.
			# Inspired by some financial applications that allow to edit the record as soon as it is added.
			# @todo Generate it with the help of album_id and protection code
			# $code = '';
			# stopper::url("albums-edit.php?id={$album_id}&code={$code}");
		}
		else
		{
			$messenger = new messenger('error', 'The record was NOT added.');
	
			$_SESSION['attempt_albums'] = $data;
			stopper::url('albums-add.php');
			
			#stopper::url('albums-add-error.php');
		}
	}
}
else
{
	# Must allow a chance to load the ADD form.
	# stopper::url('albums-direct-access-error.php');

	# Purpose of this code block is to make sure that the variable
	# gets all indices with blank data, to feed to ADD form.
	
	# A dynamic details about this record
	$details = array();
	
	if(isset($_SESSION['attempt_albums']))
	{
		$details = $_SESSION['attempt_albums'];
		unset($_SESSION['attempt_albums']);
	}

	# Validate it against the parameters in itself, plus those what we need.
	$details = $albums->validate('add', $details);
	$smarty->assign('albums', $details);
}

$smarty->assign('protection_code', $albums->code());
?>